import React, { Component } from 'react'
import { Card, Form, Input, Button, Checkbox, message } from 'antd'
import './index.scss'
import logo from 'assets/logo.png'
import { login } from 'api/user'

export default class Login extends Component {
  state = {
    loading: false,
  }
  render() {
    return (
      <div className="login">
        <Card className="login-container">
          <img src={logo} alt="" className="loginLogo" />
          <Form
            size="large"
            validateTrigger={['onChange', 'onBlur']}
            onFinish={this.onFinish}
            initialValues={{
              mobile: '13911111111',
              code: '246810',
              agree: true,
            }}
          >
            <Form.Item
              name="mobile"
              rules={[
                {
                  required: true,
                  message: '手机号不能为空',
                  validateTrigger: 'onBlur',
                },
                {
                  pattern: /^[1]([3-9])[0-9]{9}$/,
                  message: '手机格式不正确',
                },
              ]}
            >
              <Input placeholder="请输入你的手机号" />
            </Form.Item>

            <Form.Item
              name="code"
              rules={[
                {
                  required: true,
                  message: '验证码不能为空',
                  validateTrigger: 'onBlur',
                },
                {
                  pattern: /^\d{6}$/,
                  message: '验证码格式不正确',
                },
              ]}
            >
              <Input placeholder="请输入验证码" />
            </Form.Item>

            <Form.Item
              valuePropName="checked"
              name="agree"
              rules={[
                {
                  //自定义校验规则
                  validator(_, value) {
                    if (value) {
                      return Promise.resolve()
                    }
                    return Promise.reject(new Error('请阅读并同意用户协议'))
                  },
                },
              ]}
            >
              <Checkbox>我已阅读并同意相关协议</Checkbox>
            </Form.Item>

            <Form.Item>
              <Button
                type="primary"
                htmlType="submit"
                block
                loading={this.state.loading}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </Card>
      </div>
    )
  }
  onFinish = async ({ mobile, code }) => {
    this.setState({
      loading: true,
    })
    try {
      const res = await login(mobile, code)
      console.log(res)
      //1.保存token
      localStorage.setItem('GeekToken', res.data.token)
      //2.跳到首页
      this.props.history.push('/home')
      //3.成功提示
      message.success('登录成功', 1)
    } catch (err) {
      //失败提示
      message.warning(err.response.data.message, 1)
      this.setState({
        loading: false,
      })
    }
  }
}
